package tt.dz.appserver.service.task;

import java.util.ArrayList;
import java.util.Arrays;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import tt.dz.appserver.entity.vo.station.StationInfoVo;
import tt.dz.appserver.service.avro.client.oms.dzttOmsServiceProtocol;
import tt.dz.appserver.util.Constants;
import tt.dz.appserver.util.JpushUtils;
import tt.dz.appserver.util.StationOpUtils;
import tt.dz.appserver.util.date.DateUtil;
import tt.dz.appserver.util.dzcode.OmsCode;
import tt.dz.appserver.util.resource.ResourceUtils;

/**
 * spring容器初始化类
 * 
 * @author xielongfei
 *
 */
public class InitWebApp implements ApplicationListener<ContextRefreshedEvent> {

	/** 日志 */
	private final static Logger LOG = Logger.getLogger("[初始化容器:Initializing WebApp Operation Class] ");

	@Override
	public void onApplicationEvent(final ContextRefreshedEvent event) {

		// root application context 没有parent
		if (event.getApplicationContext().getParent() == null) {

			//获取oms调用接口
			final dzttOmsServiceProtocol omsService = (dzttOmsServiceProtocol) event.getApplicationContext().getBean("omsMessageProtocolRequestor");
			
			/**
			 * 新启站点数据初始化线程调用，不阻塞，不影响web启动时间
			 */
			Thread providerStationPullThread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						writeProviderStationFiles(omsService);
					} catch (Exception e) {
						LOG.error("信息：三方站点数据获取或写入出错 ：   "+e.getMessage()+"      "+ DateUtil.getDateTime());
						LOG.error(""+e);
					}
				}
			});
			providerStationPullThread.setName("三方站点数据初始化线程");
			providerStationPullThread.start();
			
			/**
			 * 新启站点数据初始化线程调用，不阻塞，不影响web启动时间
			 */
			Thread stationPullThread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						writeStationFiles(omsService);
					} catch (Exception e) {
						LOG.error("信息：站点数据获取或写入出错 ：   "+e.getMessage()+"      "+ DateUtil.getDateTime());
						e.printStackTrace();
					}
				}
			});
			stationPullThread.setName("站点数据初始化线程");
			stationPullThread.start();
			
			
			
			/**
			 * 系统变量初始化线程
			 */
			Thread setVariable =  new Thread(new Runnable() {
				@Override
				public void run() {
					setVariable();
				}
			});
			setVariable.setName("变量初始化线程");
			setVariable.start();
		}
	}
	
	/**
	 * 设置系统需要的变量
	 */
	private void setVariable(){
		
		// 设置jdbc是否显示sql
		String showSql = ResourceUtils.getProperties("cus", "jdbc.showsql");
		Constants.Jdbc.show_sql = Boolean.valueOf(showSql);

		// 运营商编码
		String merchantCode = ResourceUtils.getProperties("cus", "merchant.code");
		Constants.merchantCode = merchantCode;

		// 系统编号
		String systemCode = ResourceUtils.getProperties("cus", "system.code");
		Constants.systemCode = systemCode;

		// 极光推送KEY
		String jpush_app_key = ResourceUtils.getProperties("cus", "jpush_app_key");
		JpushUtils.jpush_app_key = jpush_app_key.toLowerCase();

		// 极光推送sercret
		String jpush_master_secret = ResourceUtils.getProperties("cus", "jpush_master_secret");
		JpushUtils.jpush_master_secret = jpush_master_secret.toLowerCase();
		
		//七牛云基本地址
		String qiniuBaseUrl = ResourceUtils.getProperties("cus", "qiniu.baseurl");
		Constants.qiniuBaseUrl = qiniuBaseUrl;
		//获取渠道集合
		String systemsCode=ResourceUtils.getProperties("cus", "systemsCode");
		Constants.systemCodes=new ArrayList<String>();
		Constants.systemCodes= Arrays.asList(systemsCode.split(",")); 
		/** 微信相关  **************/
		//获取运营商编码集合
		String merchantsCode = ResourceUtils.getProperties("cus", "merchantsCode");
		Constants.merchantCodes= new ArrayList<String>();
		Constants.merchantCodes= Arrays.asList(merchantsCode.split(","));
		//获取华体运营商编码
		String merchantHuatiCode = ResourceUtils.getProperties("cus", "merchant.huati.code");
		Constants.merchantHuatiCode=merchantHuatiCode;
		// 华体微信系统编号
		String systemHuatiWeixiCode = ResourceUtils.getProperties("cus", "system.huati.weixin.code");
		Constants.systemHuatiWeixiCode = systemHuatiWeixiCode;
		// 华体微信商户apikey 
		 String huatiWeixinApiKey=ResourceUtils.getProperties("cus", "huati.weixin.apikey");
		 Constants.huatiWeixinApiKey=huatiWeixinApiKey;
		 
		 //华体微信密钥
		 String huatiWeixinSecret=ResourceUtils.getProperties("cus", "huati.weixin.secret");
		 Constants.huatiWeixinSecret=huatiWeixinSecret;
		 //华体微信支付key 
		 String huatiWeixinPayKey=ResourceUtils.getProperties("cus", "huati.weixin.PayKey");
		 Constants.huatiWeixinPayKey=huatiWeixinPayKey; 
		 //华体微信商户号 
		 String huatiWeixinPayNum=ResourceUtils.getProperties("cus", "huati.weixin.PayNum");
		 Constants.huatiWeixinPayNum=huatiWeixinPayNum; 
		
		/***** 微信相关结束 *********/

		LOG.info("信息：设置运营商编码:" + merchantCode + " " + DateUtil.getDateTime());
		LOG.info("信息：设置JDBC SQL显示:" + Constants.Jdbc.show_sql + " " + DateUtil.getDateTime());
		LOG.info("信息：设置极光推送KEY:" + jpush_app_key + " " + DateUtil.getDateTime());
		LOG.info("信息：设置极光推送SERCRET:" + jpush_master_secret + " " + DateUtil.getDateTime());
		LOG.info("信息：设置七牛云基本地址:" + qiniuBaseUrl + " " + DateUtil.getDateTime());
		LOG.info("信息：设置华体运营商编码:" + merchantHuatiCode + " " + DateUtil.getDateTime());
		LOG.info("信息：所以运营商编码集合:" + merchantsCode + " " + DateUtil.getDateTime());
		LOG.info("华体微信apikey"+huatiWeixinApiKey+"; huatiWeixinApiKey");
		LOG.info("华体微信密钥"+huatiWeixinSecret+"; huatiWeixinSecret");
		
		LOG.info("华体微信支付key"+huatiWeixinPayKey+"; huatiWeixinPayKey");
		LOG.info("华体微信商户号"+huatiWeixinPayNum+"; huatiWeixinPayNum");
		/*********************** 电桩微信 START*********/
		// 电桩微信系统编号
		String systemDianzhuangWeixiCode = ResourceUtils.getProperties("cus", "system.dianzhuang.weixin.code");
		Constants.systemDianzhuangWeixiCode = systemDianzhuangWeixiCode;
		// 电桩微信商户apikey 
		 String dianzhuangWeixinApiKey=ResourceUtils.getProperties("cus", "dianzhuang.weixin.apikey");
		 Constants.dianzhuangWeixinApiKey=dianzhuangWeixinApiKey;		 
		 //电桩微信密钥
		 String dianzhuangWeixinSecret=ResourceUtils.getProperties("cus", "dianzhuang.weixin.secret");
		 Constants.dianzhuangWeixinSecret=dianzhuangWeixinSecret;
		 //电桩微信支付key 
		 String dianzhuangWeixinPayKey=ResourceUtils.getProperties("cus", "dianzhuang.weixin.PayKey");
		 Constants.dianzhuangWeixinPayKey=dianzhuangWeixinPayKey; 
		 //电桩微信商户号
		 String dianzhuangWeixinPayNum=ResourceUtils.getProperties("cus", "dianzhuang.weixin.PayNum");
		 Constants.dianzhuangWeixinPayNum=dianzhuangWeixinPayNum; 
		 
		 LOG.info("电桩微信系统编号"+systemDianzhuangWeixiCode+"; systemDianzhuangWeixiCode");
		 LOG.info("电桩微信商户apikey "+dianzhuangWeixinApiKey+"; dianzhuangWeixinApiKey");
		 LOG.info("电桩微信密钥"+dianzhuangWeixinSecret+"; dianzhuangWeixinSecret");
		 LOG.info("电桩微信支付key "+dianzhuangWeixinPayKey+"; dianzhuangWeixinPayKey");
		 LOG.info("电桩微信商户号"+dianzhuangWeixinPayNum+"; dianzhuangWeixinPayNum");
		 	 
		/*********************** 电桩微信 END*********/
		 
		 String baiduMapkey=ResourceUtils.getProperties("cus", "baidu.Map.key");
		 Constants.baiduMapKey=baiduMapkey; 
		 
		
		
	}
	
	/**
	 * 读取或者写入站点文件
	 * @param omsService
	 * @throws Exception
	 */
	private void writeStationFiles(dzttOmsServiceProtocol omsService) throws Exception{

		LOG.info("信息：开始获取站点数据.................................." + DateUtil.getDateTime());
		
		//调用查询接口
		String resultJsonString = omsService.getMapDataPackage(null).toString();
		//数据转换为json
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);
		
		//获取返回代码
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);
		if(OmsCode.SUCCESS.equals(code)){
			
			//获取电站原始列表
			JSONArray stationArray = omsResultObject.getJSONArray("list");
			//列表大小
			int stationArraySize = stationArray.size();
			
			//得到当前的站点
			JSONObject stationObject=null;

			LOG.info("信息：正在写入站点数据.................................." + DateUtil.getDateTime());
			//遍历大小
			for (int i = 0; i < stationArraySize; i++) {
				
				//获取的对象
				stationObject = stationArray.getJSONObject(i);
				//需要写入的对象
				StationInfoVo stationDetailVo = new StationInfoVo();	
				
				
				String stationId = stationObject.getString("station_id");
				String stationName = stationObject.getString("station_name");
				String operMerchantId = stationObject.getString("oper_merchant_id");
				String districtCode = stationObject.getString("district_code");
				String districtName = stationObject.getString("district_name");
				String parkingType = stationObject.getString("parking_type");
				String totalCharger = stationObject.getString("total_charger");
				String stationType = stationObject.getString("station_type");
				String address = stationObject.getString("address");
				String currentState = stationObject.getString("current_state");
				String directNum = stationObject.getString("direct_num");
				String alternateNum = stationObject.getString("alternate_num");
				String telNo = stationObject.getString("tel_no");
				String reviewState = stationObject.getString("review_state");
				String reviewText = stationObject.getString("review_text");
				String provinceId = stationObject.getString("province_code");
				String chargePortType=stationObject.getString("charge_port_type");
				String score=stationObject.getString("score");
				
				//位置信息列表
				JSONArray locations = stationObject.getJSONArray("locationList");
				if(locations.size()>0){
					String latitude = locations.getJSONObject(0).getString("coordinate_y");
					String longitude = locations.getJSONObject(0).getString("coordinate_x");
					stationDetailVo.setLongitude(longitude);
					stationDetailVo.setLatitude(latitude);
				}
				
				
				//封装站点字段
				stationDetailVo.setStationId(stationId);//站点ID
				stationDetailVo.setStationName(stationName);//名称
				stationDetailVo.setOperMerchantId(operMerchantId);//充电运营服务商ID
				stationDetailVo.setDistrictCode(districtCode);//区县代码
				stationDetailVo.setDistrictName(districtName);//区县名称
				stationDetailVo.setParkingType(parkingType);//停车处：1，停车楼 2，室外 3，地下室
				stationDetailVo.setTotalCharger(totalCharger);//总电桩数量
				stationDetailVo.setStationType(stationType);//站点类型 1直流2交流3混合
				stationDetailVo.setAddress(address);//详细地址
				stationDetailVo.setCurrentState(currentState);//状态 1运营总 2安装中 3规划中
				stationDetailVo.setDirectNum(directNum);//直流数量
				stationDetailVo.setAlternateNum(alternateNum);//交流数量
				stationDetailVo.setTelNo(telNo);//自营电话
				stationDetailVo.setReviewState(reviewState);//审核状态 0待审核1，审核中2，通过3，不通过
				stationDetailVo.setReviewText(reviewText);// 审核描述，说明
				stationDetailVo.setProvinceId(provinceId);// 省份ID
				stationDetailVo.setChargePortType(chargePortType);//充电接口类型：1.国标；2特斯拉；	3.ABB，	4其他
				stationDetailVo.setScore(score);//评分
				
				if("3".equals(reviewState)){
					stationDetailVo.setBooking("1");//是否可预约 1可以 0不可以
				}
				else{
					stationDetailVo.setBooking("0");//是否可预约 1可以 0不可以
				}
				
				//将对象写入文件
				StationOpUtils.writeOrUpdateStationObject(provinceId, stationName, stationDetailVo);
			}
			if(stationArraySize==0){
				LOG.error("信息：并无任何站点数据.................................." + DateUtil.getDateTime());
			}
			else{
				LOG.info("信息：站点数据写入结束.................................." + DateUtil.getDateTime());
			}
		}
		else{
			LOG.error("信息：站点数据获取出错   错误代码为："+code +"     "+ DateUtil.getDateTime());
		}
	}
	
	
	/**
	 * 读取或者写入三方站点文件
	 * @param omsService
	 * @throws Exception
	 */
	private void writeProviderStationFiles(dzttOmsServiceProtocol omsService) throws Exception{

		LOG.info("信息：开始获取第三方站点数据.................................." + DateUtil.getDateTime());
		
		//调用查询接口
		String resultJsonString = omsService.getExternalStation("").toString();
		//数据转换为json
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);

		//获取返回代码
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);
		if(OmsCode.SUCCESS.equals(code)){
			
			//获取电站原始列表
			JSONArray stationArray = omsResultObject.getJSONArray("list");
			//列表大小
			int stationArraySize = stationArray.size();
			
			//得到当前的站点
			JSONObject stationObject=null;

			LOG.info("信息：正在写入站点数据.................................." + DateUtil.getDateTime());
			//遍历大小
			for (int i = 0; i < stationArraySize; i++) {
				
				//获取的对象
				stationObject = stationArray.getJSONObject(i);
				//需要写入的对象
				StationInfoVo stationDetailVo = new StationInfoVo();	
				
				String stationId = stationObject.getString("station_id");
				String stationName = stationObject.getString("station_name");
				String operMerchantId = stationObject.getString("oper_merchant_id");
				String districtCode = stationObject.getString("district_code");
				String districtName = stationObject.getString("district_name");
				String parkingType = stationObject.getString("parking_type");
				String totalCharger = stationObject.getString("total_charger");
				String stationType = stationObject.getString("station_type");
				String address = stationObject.getString("address");
				String currentState = stationObject.getString("current_state");
				String directNum = stationObject.getString("direct_num");
				String alternateNum = stationObject.getString("alternate_num");
				String telNo = stationObject.getString("tel_no");
				String provinceId = stationObject.getString("province_code");
				String chargePortType=stationObject.getString("charge_port_type");
				String score=stationObject.getString("score");
				
				//位置信息列表
				JSONArray locations = stationObject.getJSONArray("locationList");
				if(locations.size()>0){
					String latitude = locations.getJSONObject(0).getString("coordinate_y");
					String longitude = locations.getJSONObject(0).getString("coordinate_x");
					stationDetailVo.setLongitude(longitude);
					stationDetailVo.setLatitude(latitude);
				}
				
				
				//封装站点字段
				stationDetailVo.setStationId(stationId);//站点ID
				stationDetailVo.setStationName(stationName);//名称
				stationDetailVo.setOperMerchantId(operMerchantId);//充电运营服务商ID
				stationDetailVo.setDistrictCode(districtCode);//区县代码
				stationDetailVo.setDistrictName(districtName);//区县名称
				stationDetailVo.setParkingType(parkingType);//停车处：1，停车楼 2，室外 3，地下室
				stationDetailVo.setTotalCharger(totalCharger);//总电桩数量
				stationDetailVo.setStationType(stationType);//站点类型 1直流2交流3混合
				stationDetailVo.setAddress(address);//详细地址
				stationDetailVo.setCurrentState(currentState);//状态 1运营总 2安装中 3规划中
				stationDetailVo.setDirectNum(directNum);//直流数量
				stationDetailVo.setAlternateNum(alternateNum);//交流数量
				stationDetailVo.setTelNo(telNo);//自营电话
				stationDetailVo.setProvinceId(provinceId);// 省份ID
				
				stationDetailVo.setBooking("0");//是否可预约 1可以 0不可以
				
				stationDetailVo.setChargePortType(chargePortType);//充电接口类型：1.国标；2特斯拉；	3.ABB，	4其他
				stationDetailVo.setScore(score);
				
				//将对象写入文件
				StationOpUtils.writeOrUpdateStationObject(provinceId, stationName, stationDetailVo);
			}
			if(stationArraySize==0){
				LOG.error("信息：并无任何站点数据.................................." + DateUtil.getDateTime());
			}
			else{
				LOG.info("信息：站点数据写入结束.................................." + DateUtil.getDateTime());
			}
		}
		else{
			LOG.error("信息：站点数据获取出错   错误代码为："+code +"     "+ DateUtil.getDateTime());
		}
	}
	
	
}
